from django.shortcuts import render

# Create your views here.
from django.views import View
from apps.users.models import User, Address
from django import http
import logging, json ,re
from django.contrib.auth import login, authenticate, logout
from django_redis import get_redis_connection
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from apps.users.utils import generate_email_verify_url, check_email_verify_url
from celery_tasks.email.tasks import send_email_verify_url

logger = logging.getLogger('django')

class RegisterView(View):
    def post(self, request):
        """实现注册逻辑"""
        # 接收参数：请求体中的JSON数据 request.body
        json_bytes = request.body  # 从请求体中获取原始的JSON数据，bytes类型的
        json_str = json_bytes.decode()  # 将bytes类型的JSON数据，转成JSON字符串
        json_dict = json.loads(json_str)  # 将JSON字符串，转成python的标准字典
        # json_dict = json.loads(request.body.decode())

        # 提取参数
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        sms_code_client = json_dict.get('sms_code')
        allow = json_dict.get('allow')

        # 校验参数
        # 判断是否缺少必传参数
        # all([]): 判断某些数据中是否有为空的数据
        # 只要列表中元素有任意一个为空，那么就返回False，只有所有的元素不为空，才返回True
        # all([username, password, password2, mobile, allow])
        if not all([username, password, password2, mobile, allow]):
            # 如果缺少了必传参数，就返回400的状态码和错误信息，立马终止逻辑
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 判断用户名是否满足项目的格式要求
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            # 如果用户名不满足格式要求，返回错误信息，立马终止逻辑
            return http.JsonResponse({'code': 400, 'errmsg': '参数username有误'})
        # 判断密码是否满足项目的格式要求
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            # 如果密码不满足格式要求，返回错误信息，立马终止逻辑
            return http.JsonResponse({'code': 400, 'errmsg': '参数password有误'})
        # 判断用户两次输入的密码是否一致
        if password != password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入不对'})
        # 判断手机号是否满足项目的格式要求
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        # 判断短信验证码是否正确：跟图形验证码的验证一样的逻辑
        # 提取服务端存储的短信验证码：以前怎么存储，现在就怎么提取
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)  # sms_code_server是bytes
        # 判断短信验证码是否过期
        if not sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        # 对比用户输入的和服务端存储的短信验证码是否一致
        if sms_code_client != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})

        # 判断是否勾选协议
        if allow != True:
            return http.JsonResponse({'code': 400, 'errmsg': '参数allow有误'})

        # 实现核心逻辑：保存注册数据到用户数据表
        # 由于美多商城的用户模块完全依赖于Django自带的用户模型类
        # 所以用户相关的一切操作都需要调用Django自带的用户模型类提供的方法和属性
        # 其中就包括了保存用户的注册数据，Django自带的用户模型类提行了create_user()专门保存用户的注册数据
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '注册失败'})

        # 实现状态保持：因为美多商城的需求是注册成功即登录成功
        # 我们记住当前的用户登录过的，cookie机制(不选的)，session机制（OK）
        # 如何证明当前的用户登录过，选择session机制，包含了记住登录状态和校验登录的状态
        # login()方法是Django提供的用于实现登录、注册状态保持
        # login('请求对象', '注册后或者登录认证后的用户')
        login(request, user)

        response = http.JsonResponse({'code': 0, 'errmsg': '注册成功'})
        response.set_cookie('username', user.username, max_age=14*24*3600)

        # 响应结果：如果注册成功，前端会把用户引导到首页
        return response

class UsernameCountView(View):
    # 判断用户名是否重复注册
    def get(self, request, username):
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':400, 'errmsg':'访问数据库失败'})
        return http.JsonResponse({'code':200, 'errmsg':'ok', 'count':count})

class MobileCountView(View):
    # 判断手机号是否重复注册
    def get(self, request, mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':400, 'errmsg':'访问数据库失败'})
        return http.JsonResponse({'code':200, 'errmsg':'ok', 'count':count})

class LoginView(View):
    #登录
    def post(self, request):
        # 接受参数
        json_dict = json.loads(request.body.decode())
        account = json_dict.get('username')
        password = json_dict.get('password')
        remembered = json_dict.get('remembered')

        # 校验参数
        if not all([account, password]):
            return http.JsonResponse({'code':400, 'errmsg':'缺少必要参数'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': '参数password有误'})

        # 判断输入的是用户名还是手机号
        # 实现多账号登录
        # 判断用户输入的账号是用户名还是手机号
        if re.match(r'^1[3-9]\d{9}$', account):
            # 用户输入的账号是手机号:将USERNAME_FIELD指定为'mobile'字段
            User.USERNAME_FIELD = 'mobile'
        else:
            # 用户输入的账号是用户名:将USERNAME_FIELD指定为'username'字段
            User.USERNAME_FIELD = 'username'

        user = authenticate(request=request, username=account, password=password)
        if not user:
            return http.JsonResponse({'code':400, 'errmsg':'用户名或者密码错误'})

        # 状态保持
        login(request, user)

        if remembered:
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)

        response = http.JsonResponse({'code':0, 'errmsg':'ok'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        # 响应结果
        return response

class LogoutView(View):
    # 退出登录
    def delete(self, request):
        # 清理session
        logout(request)

        response = http.JsonResponse({'code':0,'errmsg':'退出登录成功'})
        # 清理cookie
        response.delete_cookie('username')
        return response

class UserInfoView(LoginRequiredJSONMixin, View):
    # 用户中心
    # def get(self, request):
    #     """实现用户中心数据展示"""
    #     data_dict = {
    #         'code': 0,
    #         'errmsg': 'OK',
    #         'info_data': {
    #             'username': '',
    #             'mobile': '',
    #             'email': '',
    #             'email_active': ''
    #         }
    #     }
    #     return http.JsonResponse(data_dict)

    def get(self, request):
        data_dict = {
            'code': 0,
            'errmsg': 'OK',
            'info_data': {
                'username': request.user.username,
                'mobile': request.user.mobile,
                'email': request.user.email,
                'email_active': request.user.email_active
            }
        }
        return http.JsonResponse(data_dict)

class EmailView(LoginRequiredJSONMixin, View):
    # 添加邮箱
    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')
        # 校验参数
        if not email:
            return http.JsonResponse({'code':400, 'errmsg':'缺少email参数'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': 400, 'errmsg': '参数email格式错误'})
        # 核心逻辑
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '添加邮箱失败'})

        verify_url = generate_email_verify_url(user=request.user)
        send_email_verify_url.delay(email, verify_url)

        return http.JsonResponse({'code':0, 'errmsg':'ok'})

class EmailActiveView(View):
    """验证激活邮箱
    PUT /emails/verification/
    """

    def put(self, request):
        """实现验证激活邮箱的逻辑"""
        # 接收参数
        token = request.GET.get('token')

        # 校验参数
        if not token:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少token'})

        # 实现核心逻辑
        # 通过token提取要验证邮箱的用户
        user = check_email_verify_url(token=token)

        # 将要验证邮箱的用户的email_active字段设置True
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '邮箱验证失败'})

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': '邮箱验证成功'})

class AddAddressView(View):
    # 新增地址
    def post(self, request):

        # 核心：查询出当前登录用户未被逻辑删除的地址数量
        count = request.user.addresses.filter(is_deleted=False).count()
        # 判断是否超过上限
        if count >= 20:
            return http.JsonResponse({'code': 400, 'errmsg': '地址数量超过上限'})
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')  # 非必传
        email = json_dict.get('email')  # 非必传

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code':400, 'errmsg':'缺少必要参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 核心逻辑
        try:
            address = Address.objects.create(
                user=request.user,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                title=receiver,  # 默认地址的标题就是收件人
                receiver=receiver,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

            if not request.user.default_address:
                # 如果没有默认地址，就把当前的地址作为该用户的默认地址
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '新增地址有误'})

        # 响应结果
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return http.JsonResponse({'code':0, 'errmsg': 'ok', 'address':address_dict})

class AddressView(View):
    # 展示地址
    def get(self, request):
        address_list = request.user.addresses.filter(is_deleted=False)
        address_dict_list = []
        for i in address_list:
            address_dict = {
                "id": i.id,
                "title": i.title,
                "receiver": i.receiver,
                "province": i.province.name,
                "city": i.city.name,
                "district": i.district.name,
                "place": i.place,
                "mobile": i.mobile,
                "tel": i.tel,
                "email": i.email
            }
            address_dict_list.append(address_dict)

        default_address_id = request.user.default_address_id

        return http.JsonResponse({'code':0, 'errmsg':'ok', "addresses":address_dict_list, "default_address_id":default_address_id,})

class AddressUpdateView(View):
    # 修改地址
    def put(self, request, address_id):
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')  # 非必传
        email = json_dict.get('email')  # 非必传

        # 校验
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code':400, 'errmsg':'缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code':400, 'errmsg':'参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                receiver=receiver,
                title=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':400, 'errmsg':'修改地址失败'})

        # 响应结果
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return http.JsonResponse({'code':0, 'errmsg':'ok', 'address':address_dict})

    # 删除地址
    def delete(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted = True
            address.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':400, 'errmsg':'删除地址失败'})

        return http.JsonResponse({'code': 0, 'errmsg': '删除地址成功'})

class UpatePasswordView(View):
    # 修改密码
    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        old_password = json_dict.get('old_password')
        new_password = json_dict.get('new_password')
        new_password2 = json_dict.get('new_password2')
        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return http.JsonResponse({'code':400, 'errmsg':'缺少必传参数'})
        result = request.user.check_password(old_password)
        if not result:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '原始密码不正确'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.JsonResponse({'code': 400, 'errmsg': '密码最少8位,最长20位'})
        if new_password != new_password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入密码不一致'})
        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '修改密码失败'})
        logout(request)
        response = http.JsonResponse({'code':0, 'errmsg':'ok'})
        response.delete_cookie('username')
        return response
